<?php

namespace C\S\Other;

use C\L\Service;
use C\M\Slide as SlideModel;

class Slide extends Service
{
    protected function setModel()
    {
        $this->model = new SlideModel();
    }

    /**
     * 轮播图相关配置
     *
     * @param int $currentPage
     * @param int $perPage
     * @return mixed
     **/
    public function getConfig()
    {
        return [
            'type' => [
                'home_banner'         => '首页轮播图',
                'group_buying_banner' => '团购页轮播图',
            ],
            'status' => [
                0 => '禁用',
                1 => '启用',
            ],
        ];
    }

    /**
     * 列出轮播图
     *
     * @param string $type
     * @param int $status
     * @param int $currentPage
     * @param int $perPage
     * @return mixed
     **/
    public function paginate($type, $status, $currentPage, $perPage)
    {
        $query = SlideModel::query()->where('1=1');

        if ($type) {
            $query = $query->andWhere(
                'types LIKE :type:',
                [ 'type' => '%' . $type . '%']
            );
        }

        if ($status) {
            $query = $query->andWhere(
                'status = :status:',
                ['status' => $status]
            );
        }

        $builder = $query
          ->orderBy("sort ASC, id DESC")
          ->createBuilder();

        return $this->paginateByBuilder($builder, $currentPage, $perPage);
    }

    /**
     * 查看轮播图
     *
     * @param int $id
     * @return mixed
     **/
    public function view($id)
    {
        return SlideModel::findById($id);
    }

    /**
     * 添加轮播图
     *
     * @param array $params
     * @return mixed
     **/
    public function store($params)
    {
        $slide = new SlideModel();

        return $slide->save($params) ? $slide : false;
    }

    /**
     * 更新轮播图
     *
     * @param int $id
     * @param array $params
     * @return mixed
     **/
    public function newUpdate($id, $params)
    {
        $slide = SlideModel::findById($id);

        if (!$slide) {
            return false;
        }

        return $slide->save($params) ? $slide : false;
    }

    /**
     * 删除轮播图
     *
     * @param int $id
     * @param array $params
     * @return mixed
     **/
    public function delete($id)
    {
        $slide = SlideModel::findById($id);

        if (!$slide) {
            return false;
        }

        return $slide->delete();
    }
}
